package com.yuan.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.yuan.blockhandler.BlockHandler;
import com.yuan.fallbackhandler.FallbackHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
@Slf4j
public class HelloController {
    @Value("${tempValue}")
    private String tempValue;
    //访问次数
    private static int count;

    /**
     * value 是资源名称，要确保与Sentinel服务中设置的一致且唯一，与Spring的AOP中的切点概念很相似
     * blockHandler 是处理BlockException的接口名称，接口默认需要和原方法在同一个类中
     * 如果希望使用其他类的函数，需要指定 blockHandlerClass 为对应的类的 Class 对象，注意对应的函数必需为static 函数，否则无法解析。
     */
    @GetMapping(value = "/hi")
    @SentinelResource(value = "sayHello", blockHandlerClass = BlockHandler.class, blockHandler = "blockHandlerForSayHello")
    public String sayHello(@RequestParam(name = "name") String name) {
        log.info("Provider Hello World : {},时间：{}", name, System.currentTimeMillis());
        return "Hello World: " + name;
    }

    @GetMapping(value = "appName")
    public String getAppName() {
        log.info("Application Name :{}", tempValue);
        return "Application Name : " + tempValue;
    }

    @GetMapping("/degrade")
    @SentinelResource(value = "testDegradeRule",fallbackClass = FallbackHandler.class,fallback = "fallbackHandlerForDegradeRule")
    public String testDegradeRule() {
        if ((count++ & 1) == 1) {
            throw new RuntimeException("人为制造异常");
        } else {
            return "降级测试：不发生异常";
        }
    }


}
